<template>
  <div>
    <div>
      <el-input placeholder="请输入学号" v-model="sno" style="width: 30%"></el-input>
      <el-input placeholder="请输入姓名" v-model="sname" style="width: 30%"></el-input>
      <el-button :icon="Search" @click="handleSearch">搜索</el-button>
    </div>
  </div>
  <div style="display: flex;margin-top: 10px">
    <el-button type="primary" :icon="Plus" @click="handleAdd" style="margin-left: 0;">添加数据</el-button>
    <el-button type="danger" :icon="Delete" style="margin-left: 80%" @click="handleDelList" v-if="multipleSelection.length>0">删除选中数据</el-button>
  </div>
  <div style="padding: 20px;">
    <el-table class="currentTable" :data="students"
              @selection-change="handleSelectChange"
              @sort-change="handleSortChange"
              :header-cell-style="{ background: '#f6f9fa'}">
      <el-table-column type="selection"/>
      <!--el-table-column列-->
      <el-table-column prop="sno" label="学号" sortable></el-table-column>
      <el-table-column prop="sname" label="姓名"></el-table-column>
      <el-table-column prop="photo" label="头像">
        <template #default="{ row }">
          <img :src="row.photo" alt="学生头像" style="width: 50px; height: 50px; border-radius: 50%; object-fit: cover;">
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别"></el-table-column>
      <el-table-column prop="birthday" label="生日">
        <template #default="{ row }">
          {{ formatDate(row.birthday) }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="classid" label="班级"></el-table-column>
      <el-table-column prop="signature" label="个性签名"></el-table-column>
      <el-table-column label="操作" min-width="180">
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,10,20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="justify-content: center;margin-top: 8px"
    />
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" label-width="80px">
        <!-- 学号 -->
        <el-form-item label="学号" prop="sno">
          <el-input v-model="form.sno" :disabled="canEdit"></el-input>
        </el-form-item>
        <!-- 姓名 -->
        <el-form-item label="姓名" prop="sname">
          <el-input v-model="form.sname" :disabled="canEdit"></el-input>
        </el-form-item>
        <!-- 头像 -->
        <el-form-item label="头像" prop="photo">
          <img :src="form.photo" alt="学生头像"  style="width: 50px; height: 50px; border-radius: 50%; object-fit: cover;" />
        </el-form-item>
        <!-- 性别 -->
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio value="男">男</el-radio>
            <el-radio value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 生日 -->
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
              v-model="form.birthday"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
          </el-date-picker>
        </el-form-item>
        <!-- 电话 -->
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <!-- 地址 -->
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <!-- 班级号 -->
        <el-form-item label="班级号" prop="classid">
          <el-input v-model="form.classid"></el-input>
        </el-form-item>
        <!-- 个性签名 -->
        <el-form-item label="个性签名" prop="signature">
          <el-input v-model="form.signature"></el-input>
        </el-form-item>
        <!-- 权限等级 -->
        <el-form-item label="权限等级" prop="level">
          <el-input v-model="form.level"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="dialogOk">确 定</el-button>
    </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {Delete, Edit, Plus, Search} from "@element-plus/icons-vue";
import axios from "axios";
import {onMounted, ref,computed} from "vue";
import {ElMessage,ElMessageBox} from "element-plus";
const students=ref([])
const currentPage=ref(1)
const pageSize=ref(10)
const total=ref(0)
const sno=ref('')
const sname=ref('')

const formatDate = (date) => {
  if (!date) return '';
  const parsedDate = new Date(date);
  if (isNaN(parsedDate)) return date; // 如果解析失败，返回原值
  const year = parsedDate.getFullYear();
  const month = String(parsedDate.getMonth() + 1).padStart(2, '0');
  const day = String(parsedDate.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

//组件挂载到DOM后执行后端数据加载
onMounted(()=>{
  getData();
})
const getData=()=>{
  axios.get("http://localhost:8080/student/findByPage",{
    params:{
      pageNum:currentPage.value,
      pageSize:pageSize.value,
      sname: sname.value,
      sno: sno.value
    }
  }).then(res=>{
    students.value=res.data.records
    total.value=res.data.total
  }).catch(err=>{
    console.log(err)
  })
}
//切换每页显示条数
const handleSizeChange=(pagesize)=>{
  pageSize.value=pagesize
  getData();
}
//切换当前页码
const handleCurrentChange=(pageNum)=>{
  currentPage.value=pageNum
  getData();
}
const dialogVisible=ref(false)
const form=ref({});
const dialogType=ref('');
const canEdit=ref(false)
function handleAdd() { // 添加按钮点击事件
  form.value = {
    sno: '',
    sname: '',
    gender: "男",
    level: ''
  };
  dialogType.value = 'add';
  canEdit.value=false;
  dialogVisible.value = true;
}

function handleEdit(row) { // 编辑按钮点击事件
  dialogVisible.value = true;
  form.value = { ...row };
  canEdit.value=true;
  dialogType.value = 'edit';
}
const dialogTitle = computed(()=>{//弹窗标题
  return dialogType.value === 'add' ? '添加学生信息' : '编辑学生信息';
})
const dialogOk = () => {
  dialogVisible.value = false;

  if (dialogType.value === 'add') {
    const newStudent = { ...form.value };
    axios.post("http://localhost:8080/student", newStudent)
        .then(response => {
          ElMessage({
            type: 'success',
            message: '添加成功！',
          });
          getData();
        })
        .catch(error => {
          console.log(error);
        });
  } else {
    const studentId = form.value.sno;
    const updatedStudent = { ...form.value };
    axios.put(`http://localhost:8080/student/${studentId}`, updatedStudent)
        .then(response => {
          ElMessage({
            type: 'success',
            message: '修改成功！',
          });
          getData();
        })
        .catch(error => {
          console.log(error);
        });
  }
};
// 删除行数据
const delRow = (row) => {
  // 获取要删除的用户的 ID
  const sId = row.sno;
  // 发送 HTTP DELETE 请求来删除用户
  axios.delete(`http://localhost:8080/student/${sId}`)
      .then(response => {
        localStorage.setItem('delete',JSON.stringify(response.data));
        getData();
      })
      .catch(error => {
        console.error(error);
      })
}
//处理删除按钮点击事件
function handleDelete(row) {
  ElMessageBox.confirm(
      '您确定要删除学号为【' + row.sno + '】的数据吗?',
      '危险操作',

  ).then(() => {
    delRow(row)
    ElMessage({
      type: 'success',
      message: '完成删除！',
    })
  })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除!',
        })
      })
}
//多选事件
let multipleSelection = ref([]);
const handleSelectChange = (val) => {
  multipleSelection.value=[]
  val.forEach(item=>{
    multipleSelection.value.push(item.sno)
  })
}
//删除多条数据
const handleDelList=()=>{
  ElMessageBox.confirm(
      '您确定要删除选中的数据吗?',
      '危险操作',
      {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}
  ).then(() => {
    const studentIds=multipleSelection.value;
    window.alert(studentIds)
    axios.delete('http://localhost:8080/students',{
      method: 'post',
      data: JSON.stringify(studentIds), // 将数组转换为JSON字符串
      headers: {
        'Content-Type': 'application/json'
      }
    })
        .then(response=>{

          getData();
          ElMessage({
            type: 'success',
            message: '完成批量删除！'
          })
        })
        .catch(error=>{
          console.log(error);
          ElMessage({
            type: 'error',
            message: '删除失败!'
          })
        })
        .catch(()=>{
          ElMessage({
            type: 'info',
            message: '取消删除!',
          })
        })
  })
}
// 搜索事件
const text=ref("");
const handleSearch=()=>{
  getData()
}
// 排序事件
const handleSortChange = (sortData) => {
  const {prop, order} = sortData;
  students.value=students.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else {
      return a[prop] < b[prop] ? 1 : -1;
    }
  });

}
</script>

